package za.org.jcicada.genss.sensor.impl;

import java.util.Map;
import java.util.TreeMap;

import za.org.jcicada.genss.sensor.ISensorType;
import za.org.jcicada.genss.sensor.IStatusStrategy;
import za.org.jcicada.genss.sensor.SensorStatus;

/**
 * Records pairs of statuses with their upper thresholds. Iterate until a threshold
 * is found which is greater than the current value and use the corresponding
 * status.
 * @author rcrida
 */
public class StatusStrategyFloat implements IStatusStrategy {

	/** Map of threshold to status in ascending order */
	TreeMap<Float,SensorStatus> statusMap;
	
	/** Sensor type that this strategy is for */
	TypeFloat type;
	
	public StatusStrategyFloat(TypeFloat type, TreeMap<Float,SensorStatus> statusMap) {
		this.type = type;
		this.statusMap = statusMap;
	}
	
	/** Construct from string
	 * @param type the float sensor type that this strategy is for
	 * @param params in form threshold=>status,t2=>s2,Infinity=>s3
	 */
	public StatusStrategyFloat(TypeFloat type, String params) {
		this.type = type;
		statusMap = new TreeMap<Float, SensorStatus>();
		for (String option : params.split(",")) {
			String[] kv = option.split("=>");
			statusMap.put(Float.valueOf(kv[0]), SensorStatus.valueOf(kv[1]));
		}
	}
	
	public SensorStatus getStatus(Object value) throws InvalidSensorValue {
		Float number = (Float)value;
		for (Map.Entry<Float, SensorStatus> entry : statusMap.entrySet()) {
			if (entry.getKey().compareTo(number) >= 0)
				return entry.getValue();
		}
		return SensorStatus.UNKNOWN;
	}

	public boolean isValidSensorType(ISensorType sensorType) {
		return type.equals(sensorType);
	}

}
